package com.cy.store.controller;

import com.cy.store.service.ICartService;
import com.cy.store.util.JsonResult;
import com.cy.store.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author Luo Sheng
 * @school YiBin university
 * @create 2022-12-12 16:13
 */
@RestController
@RequestMapping("/carts")
public class CartController extends BaseController{
    @Autowired
    private ICartService cartService;

    @PostMapping("/add_to_cart")
    public JsonResult<Void> addToCart (Integer pid, Integer amount,
                                      HttpSession session){
        // 调用业务对象执行添加到购物车
        cartService.addToCart(getUidFromSession(session), pid, amount, getUsernameFromSession(session));

        // 返回成功
        return new JsonResult<Void>(OK);
    }

    /**
     * 查看用户购物车
     * @param session
     * @return
     */
    @GetMapping({"", "/"})
    public JsonResult<List<CartVO>> getVOByUid(HttpSession session) {
        // 调用业务对象执行查询数据
        List<CartVO> data = cartService.getVOByUid(getUidFromSession(session));

        // 返回成功与数据
        return new JsonResult<List<CartVO>>(OK, data);
    }

    /**
     * 减少商品中的数量
     * @param cid
     * @param session
     * @return
     */
    @RequestMapping("{cid}/num/add")
    public JsonResult<Integer> addNum(@PathVariable("cid") Integer cid, HttpSession
            session) {
        // 调用业务对象执行减少数量
        Integer data = cartService.updateNum(cid, getUidFromSession(session), getUsernameFromSession(session), ADD_PRODUCT_NUM);

        // 返回成功
        return new JsonResult<Integer>(OK, data);
    }

    /**
     * 增加购物车中的商品数量
     * @param cid
     * @param session
     * @return
     */
    @RequestMapping("{cid}/num/reduce")
    public JsonResult<Integer> reduceNum(@PathVariable("cid") Integer cid, HttpSession
            session) {
        // 调用业务对象执行增加数量
        Integer data = cartService.updateNum(cid, getUidFromSession(session), getUsernameFromSession(session), REDUCE_PRODUCT_NUM);

        // 返回成功
        return new JsonResult<Integer>(OK, data);
    }

    @PostMapping("/deleteCart")
    public JsonResult<Void> deleteCart(@RequestBody Map<String,List<Integer>> data,
                                       HttpSession session){
        List<Integer> cids = data.get("cids");
        Integer uid = getUidFromSession(session);
        cartService.deleteCart(uid, cids);
        return new JsonResult(OK);
    }

    @GetMapping("/list")
    public JsonResult<List<CartVO>> getVOByCids(Integer[] cids, HttpSession session)
    {
        // 调用业务对象执行查询数据
        List<CartVO> data = cartService.getVOByCids(getUidFromSession(session), cids);
        // 返回成功与数据
        return new JsonResult<>(OK, data);
    }

}
